package com.daffodil.storage.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import com.daffodil.storage.client.SftpStorageClient;
import com.daffodil.storage.client.sftp.SessionPooledFactory;
import com.daffodil.storage.client.sftp.SftpSessionPool;
import com.daffodil.storage.properties.SftpProperties;
import com.daffodil.storage.properties.StorageProperties;
import com.jcraft.jsch.Session;

/**
 * 使用SFTP方式存储文件，本质也是磁盘存储
 * <p>SFTP: Secure File Transfer Protocol 安全文件传输协议</p>
 * @author yweijian
 * @date 2023年11月3日
 * @version 1.0
 * @description
 */
@Component
@Configuration
@ConditionalOnProperty(name = StorageProperties.NAME, havingValue = StorageProperties.SFTP)
public class SftpClientConfig {

    @Bean
    @ConditionalOnMissingBean
    public SessionPooledFactory sessionPooledFactory(StorageProperties storageProperties) {
        SftpProperties properties = storageProperties.getSftp();
        SessionPooledFactory factory = new SessionPooledFactory();
        factory.setHost(properties.getHost());
        factory.setPort(properties.getPort());
        factory.setUsername(properties.getUsername());
        factory.setPassword(properties.getPassword());
        factory.setSoTimeout(properties.getSoTimeout());
        return factory;
    }

    @Bean
    @ConditionalOnMissingBean
    public SftpStorageClient sftpStorageClient(StorageProperties storageProperties, SessionPooledFactory factory) {
        SftpProperties properties = storageProperties.getSftp();
        GenericObjectPoolConfig<Session> config = new GenericObjectPoolConfig<Session>();
        SftpSessionPool pool = new SftpSessionPool(factory, config);
        return new SftpStorageClient(pool, properties.getConnectTimeout());
    }
}
